'''
Created on Jun 1, 2009

@author: morales
'''

import commands
import numpy as np
import PolymorphismTable as pt

def runMS( parameters ):
    newCommand = 'ms %s' % (parameters)
    msOut = commands.getoutput( newCommand )

    return msOut


def readMS( filename ):

    f = open( filename, 'r')

    header = f.readline().split()
    numChromosomes = int(header[1])
    numSimulations = int(header[2])
    
    f.readline() #ignore
    f.readline()
    f.readline()
    
    polyTables = []
    
    for simItr in range(numSimulations):
        segLine = f.readline().split()
        numSegSites = int(segLine[1])
        
        if numSegSites > 0:
            posLine = f.readline()
    
            a = []
            
            for chrItr in range(numChromosomes):
                chr = str(f.readline().rstrip())
    
                polys = []            
                for siteItr in range( len(chr) ):
                    polys.append( int(chr[siteItr]) )
            
                a.append( np.array( polys ))
            
            data = np.array(a)
            poly = pt.PolymorphismTable(posLine, data)
            
            polyTables.append( poly )
        
        else:
            f.readline()
        
        f.readline()
        f.readline()
    
    return polyTables

